package org.jederik.studip.android.provider;

import org.jederik.android.provider.StudIP.*;
import org.jederik.studip.android.Const;
import org.jederik.studip.android.view.Preferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Hilfsklasse für den Zugriff auf die lokale Datenbank.
 * @author Jann-Frederik Laß
 *
 */
public class DatabaseHelper extends SQLiteOpenHelper {
	
	// Name der Datenbank:
	private static final String DATABASE_NAME = "studip";
	
	// Datenbankversion:
	private static final int DATABASE_VERSION = 49;
	
	// Wird benötigt, um beim Updaten der DB-Version auch den 
	// Synchronisationsstatus in den Einstellungen zurückzusetzen:
	private Context context;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(Schedules.SQL_CREATE);
		db.execSQL(Feed.SQL_CREATE);
		db.execSQL(Mycourses.SQL_CREATE);
		db.execSQL(News.SQL_CREATE);
		db.execSQL(Messages.SQL_CREATE);
		db.execSQL(MessagesSent.SQL_CREATE);
		db.execSQL(CourseDetails.SQL_CREATE);
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL(Schedules.SQL_DROP);
		db.execSQL(Feed.SQL_DROP);
		db.execSQL(Mycourses.SQL_DROP);
		db.execSQL(News.SQL_DROP);
		db.execSQL(Messages.SQL_DROP);
		db.execSQL(MessagesSent.SQL_DROP);
		db.execSQL(CourseDetails.SQL_DROP);
		
		SharedPreferences.Editor editor = context.getSharedPreferences(Const.PREFS_NAME, 0).edit();
		editor.remove(Preferences.LAST_FEED_SYNC);
		editor.remove(Preferences.LAST_SCHEDULE_SYNC);
		editor.remove(Preferences.LAST_FEED_VIEW);
		editor.commit();


		onCreate(db);
	}

}
